// /* eslint-disable @typescript-eslint/no-unused-vars */
import { productBasicConfigAdd, productBasicConfigModify, productBasicConfigRemove } from "@/api/modules/iot/product";
import Empty from "@/components/Empty";
import { SchemaItem } from "@/components/JsonSchemaForm/interface";
import ProTable from "@/components/ProTable/index.vue";
import { ColumnProps } from "@/components/ProTable/interface";
import { SchemaNodeKey } from "@/utils/constants";
import mittBus from "@/utils/mittBus";
import { parseConfigSchemaFromGateway, parseSchemaToTreeList, profileConfigGateway } from "@/utils/schema";
import { showTips } from "@/utils/util";
import { Action, ElMessageBox } from "element-plus";
import { defineComponent } from "vue";
import { useRoute } from "vue-router";
import SchemaForm from "../components/SchemaForm";

/**
 * 设备参数信息,scheme中的config下面子设备参数信息（排除sensor节点）
 * 相关参数：设备接入端口、地址、采集周期、上报周期
 */
export default defineComponent({
	emits: [],
	setup() {
		const route = useRoute();
		//网关scheme：设备参数配置模型
		const schema = inject<any>(SchemaNodeKey.schema);
		//网关profile：设备参数配置值
		const profile = inject<any>(SchemaNodeKey.profile);
		let sensor = parseConfigSchemaFromGateway(schema.value);
		let gateway = profileConfigGateway(profile.value);
		const paramDialog = reactive<any>({
			isAdd: false,
			title: "",
			paramData: {
				key: "",
				title: "",
				description: "",
				type: "string",
				valid: true,
				rules: []
			},
			visible: false
		});
		//打开变量弹窗
		const poenDailog = (item?: SchemaItem) => {
			paramDialog.isAdd = item ? false : true;
			paramDialog.title = item ? "修改变量【" + item.key + "】" : "添加变量";
			paramDialog.paramData = item || { type: "string", valid: true };
			paramDialog.visible = true;
		};
		//刷新网关数据
		const refreshGatewayDetail = () => {
			mittBus.emit("refreshGatewayDetail");
		};
		//变量删除
		const delSensor = (item: SchemaItem) => {
			ElMessageBox.alert("確定刪除变量【" + item.key + "】", "刪除确认", {
				confirmButtonText: "确定",
				callback: async (action: Action) => {
					if (action == "cancel") return;
					let { code, message } = await productBasicConfigRemove({ idSn: route.query.sn as string, key: item.key });
					showTips(code, "删除变量配置", message) && refreshGatewayDetail();
				}
			});
		};
		//变量保存
		const submit = () => {
			let url = paramDialog.isAdd ? productBasicConfigAdd : productBasicConfigModify;
			let obj: any = {};
			obj[paramDialog.paramData.key] = paramDialog.paramData;
			url({ idSn: route.query.sn as string, data: obj }).then(async res => {
				let ok = showTips(res.code, "新增变量配置", res.message);
				if (ok) {
					paramDialog.visible = false;
					//新增变量成功后插入参数值的key
					gateway[paramDialog.paramData.key] = "";
					refreshGatewayDetail();
				}
			});
		};
		//监听设备模型值变化
		watch(
			() => schema.value,
			() => {
				//刷新数据
				sensor = parseConfigSchemaFromGateway(schema.value);
				// gateway = profileBasicConfig(gatewayProfile.value);
				proTable.value.getTableList();
			}
		);
		//写入列表数据
		const getTableList = async () => {
			let treeList = parseSchemaToTreeList(sensor);
			return { result: { records: treeList } };
		};
		let treeData = ref<any>([]);
		//列表数据转换
		const dataCallback = (data: any) => {
			treeData.value = data.records;
			return {
				datalist: data.records
				// total: data.total,
				// pageIndex: data.current,
				// pageSize: data.size
			};
		};

		const proTable = ref<any>();
		// 表格配置项
		const columns = ref<ColumnProps[]>([
			{ prop: "title", label: "属性名称" },
			{ prop: "key", label: "属性标识" },
			{ prop: "description", label: "属性描述" },
			{ prop: "operation", label: "操作", fixed: "right", width: 130 }
		]);
		return () => {
			return (
				<div class="">
					<SchemaForm
						v-model:visible={paramDialog.visible}
						title={paramDialog.title}
						onSubmit={() => submit()}
						formData={paramDialog.paramData}
						isAdd={paramDialog.isAdd}
						treeData={treeData.value}
					></SchemaForm>
					<ProTable
						ref={proTable}
						selectId="key"
						columns={columns.value}
						requestApi={getTableList}
						dataCallback={dataCallback}
						pagination={false}
					>
						{{
							tableHeader: () => {
								return (
									<el-button onClick={() => poenDailog()} type="primary">
										<i class="iconfont iconbx-plus" />
										添加
									</el-button>
								);
							},
							cardBody: (scope: any) => {
								return (
									<div class="pt-4">
										<div class="flex leading-8">
											<div class="item-label pr-4 w-1/2 text-right">属性标识</div>
											<div class="item-text pl-4">{scope.row.key}</div>
										</div>
										<div class="flex leading-8">
											<div class="item-label pr-4 w-1/2 text-right">属性名称</div>
											<div class="item-text pl-4">{sensor[scope.row.key].title || "--"}</div>
										</div>
										<div class="flex leading-8">
											<div class="item-label pr-4 w-1/2 text-right">属性描述</div>
											<div class="item-text pl-4">{sensor[scope.row.key].description || "--"}</div>
										</div>
										<div class="flex leading-8">
											<div class="item-label pr-4 w-1/2 text-right">数据类型</div>
											<div class="item-text pl-4">{sensor[scope.row.key].type || "--"}</div>
										</div>
										<div class="bg-gray-200 mt-2 flex h-9">
											<el-link
												class="flex-1"
												type="danger"
												onClick={() => {
													delSensor(sensor[scope.row.key] || scope.row.key);
												}}
											>
												删除
											</el-link>
											<el-link
												class="flex-1"
												type="primary"
												onClick={() => {
													sensor[scope.row.key].key = scope.row.key;
													poenDailog(sensor[scope.row.key]);
												}}
											>
												修改
											</el-link>
										</div>
									</div>
								);
							},
							operation: (scope: any) => {
								return (
									<>
										<el-link
											class="flex-1"
											type="danger"
											onClick={() => {
												delSensor(sensor[scope.row.key] || scope.row.key);
											}}
										>
											删除
										</el-link>
										<el-link
											class="flex-1"
											type="primary"
											onClick={() => {
												sensor[scope.row.key].key = scope.row.key;
												poenDailog(sensor[scope.row.key]);
											}}
										>
											修改
										</el-link>
									</>
								);
							},
							empty: () => {
								return (
									<div>
										<Empty
											class="text-left leading-6"
											onAdd={() => poenDailog()}
											btnText="添加配置"
											title="网关没配置参数项"
											subtitle="您可以在网关模型中定义子设备参数模型"
										/>
									</div>
								);
							}
						}}
					</ProTable>
				</div>
			);
		};
	}
});
